package com.wwtech.epp.ui.activity.work;

import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.entity.SignConfig;
import com.wwtech.epp.entity.TodaySign;
import com.wwtech.epp.entity.sign.Config;
import com.wwtech.epp.ui.activity.work.component.DaggerPunchCardComponent;
import com.wwtech.epp.ui.activity.work.contract.PunchCardContract;
import com.wwtech.epp.ui.activity.work.module.PunchCardModule;
import com.wwtech.epp.ui.activity.work.presenter.PunchCardPresenter;
import com.wwtech.epp.utils.SignUtil;
import com.wwtech.epp.utils.ToastUtil;
import com.wwtech.epp.view.GlideCircleTransform;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/08/28 16:45:05
 */

public class PunchCardActivity extends BaseActivity implements PunchCardContract.View, GeocodeSearch.OnGeocodeSearchListener {

    @Inject
    PunchCardPresenter mPresenter;
    @BindView(R.id.avater)
    ImageView avater;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.company)
    TextView company;
    @BindView(R.id.now_time)
    TextView nowTime;
    @BindView(R.id.card1)
    TextView card1;
    @BindView(R.id.card2)
    TextView card2;
    @BindView(R.id.iv_card_one)
    ImageView ivCardOne;
    @BindView(R.id.tv_one_card)
    TextView tvOneCard;
    @BindView(R.id.iv_card_two)
    ImageView ivCardTwo;
    @BindView(R.id.tv_two_card)
    TextView tvTwoCard;
    @BindView(R.id.tv_one_desc)
    TextView tvOneDesc;
    @BindView(R.id.tv_two_desc)
    TextView tvTwoDesc;
    @BindView(R.id.beizhu)
    EditText beizhu;
    private LocationManager locationManager;
    private String locationProvider;
    private String longtitude;
    private String latitude;
    private SignConfig.DataBean signConfig;
    private String location = "";
    private LatLonPoint mLatLonPoint;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            // TODO Auto-generated method stub
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    double locationType = amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    double mlatitude = amapLocation.getLatitude();//获取纬度
                    double mlongtitude = amapLocation.getLongitude();//获取纬度
                    KLog.e("Amap==经度：纬度", "locationType:"+locationType+",latitude:"+mlatitude);
                    longtitude = mlongtitude + "";
                    latitude = mlatitude + "";
                    GeocodeSearch geocoderSearch = new GeocodeSearch(PunchCardActivity.this);
                    geocoderSearch.setOnGeocodeSearchListener(PunchCardActivity.this);//和上面一样
                    // 第一个参数表示一个Latlng(经纬度)，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                    RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(mlatitude, mlongtitude), 200, GeocodeSearch.AMAP);
                    geocoderSearch.getFromLocationAsyn(query);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    KLog.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private TodaySign mTodaySign;
    private Config config;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_punch_card);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("打卡");
//        getLocation(this);
        gaode();
    }

    private void gaode() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);

        /**
         * 获取一次定位
         */
        //该方法默认为false，true表示只定位一次
        mLocationOption.setOnceLocation(true);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }

    @Override
    protected void initData() {
        Map<String, String> map = new HashMap<>();
        mPresenter.getSignConfig(map);
        Glide.with(this)
                .load(ContainValue.loginUserInfo.getAvatar())
                .transform(new GlideCircleTransform(this))
                .into(avater);
        name.setText(ContainValue.userLogin.getData().getNickName());
        company.setText(ContainValue.loginUserInfo.getDepartment());
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        nowTime.setText(sdf.format(new Date(Calendar.getInstance().getTimeInMillis())));

    }

    @Override
    protected void setupActivityComponent() {
        DaggerPunchCardComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .punchCardModule(new PunchCardModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        mLocationClient.stopLocation();
    }

    @Override
    public void setPresenter(PunchCardContract.PunchCardContractPresenter presenter) {
        mPresenter = (PunchCardPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    /**
     * 获取了打卡配置的返回
     * @param dataBean
     */
    @Override
    public void setSignConfig(SignConfig.DataBean dataBean) {
        signConfig = dataBean;
    }

    @Override
    public void setTodaySignInfo(TodaySign todaySign) {
        mTodaySign = todaySign;
        String scard1 = "";
        String scard2 = "";
        config = new Gson().fromJson(signConfig.getConfig(), Config.class);
        //判断当前时间是不是在上班时间或者下班时间,如果不是，就把输入备注的edittext显示出来
        if (!SignUtil.isNormalTime(config.getWorkBeginTime(),config.getWorkEndTime(), nowTime.getText().toString()) && !SignUtil.isNormalTime(config.getDoneBeginTime(), config.getDoneEndTime(), nowTime.getText().toString())) {
            beizhu.setVisibility(View.VISIBLE);
        }
        if (mLatLonPoint != null && !SignUtil.isInSignArea(config.getDistance(), config.getLocations(), new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()))) {
            beizhu.setVisibility(View.VISIBLE);
        }
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.CHINA);
        Date date = new Date();
        scard1 = "打卡 " + config.getWorkBeginTime() + "~" + config.getWorkEndTime();
        scard2 = "打卡 " + config.getDoneBeginTime() + "~" + config.getDoneEndTime();
        //上班已经打卡
        if (todaySign.getData() != null && todaySign.getData().size() != 0) {
            if (todaySign.getData().get(0).getType() == 0) {
                try {
                    date = sdr.parse(todaySign.getData().get(0).getUpdateTime());
                } catch (Exception e) {
                    e.printStackTrace();
                    date = new Date();
                }
                ivCardOne.setImageDrawable(getResources().getDrawable(R.mipmap.work_clock02));
                card1.setVisibility(View.GONE);
                scard1 = scard1 + "(上班" + sdf.format(date) + ")";
            }
            if (todaySign.getData().size() == 2 && todaySign.getData().get(1).getType() == 0) {
                try {
                    date = sdr.parse(todaySign.getData().get(1).getUpdateTime());
                } catch (Exception e) {
                    e.printStackTrace();
                    date = new Date();
                }
                ivCardOne.setImageDrawable(getResources().getDrawable(R.mipmap.work_clock02));
                card1.setVisibility(View.GONE);
                scard1 = scard1 + "(上班" + sdf.format(date) + ")";
            }
        }
        if (todaySign.getData() != null && todaySign.getData().size() != 0) {
            if (todaySign.getData().get(0).getType() == 1) {
                card2.setText("更新打卡");
                try {
                    date = sdr.parse(todaySign.getData().get(0).getUpdateTime());
                } catch (Exception e) {
                    e.printStackTrace();
                    date = new Date();
                }
                scard2 = scard2 + "(下班" + sdf.format(date) + ")";
            }
            if (todaySign.getData().size() == 2 && todaySign.getData().get(1).getType() == 1) {
                card2.setText("更新打卡");
                try {
                    date = sdr.parse(todaySign.getData().get(1).getUpdateTime());
                } catch (Exception e) {
                    e.printStackTrace();
                    date = new Date();
                }
                scard2 = scard2 + "(下班" + sdf.format(date) + ")";
            }
        }
        tvOneCard.setText(scard1);
        tvTwoCard.setText(scard2);
    }

    @Override
    public void signBack() {
        ToastUtil.displayShortToast("打卡成功");
        beizhu.setText("");
        initData();
    }

    @OnClick({R.id.card1, R.id.card2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.card1:
                if (SignUtil.isNormalTime(config.getWorkBeginTime(), config.getWorkEndTime(), nowTime.getText().toString().trim()) && SignUtil.isInSignArea(config.getDistance(), config.getLocations(), new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()))) {
                    Map<String, String> map = new HashMap<>();
                    map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                    map.put("type", "0");
                    map.put("lng", longtitude);
                    map.put("lat", latitude);
                    map.put("location", location);
                    map.put("signDesc", beizhu.getText().toString().trim());
                    mPresenter.signUpdate(map);
                } else {
                    if (beizhu.getText().toString().trim().equals("")) {
                        ToastUtil.displayShortToast("打卡时间或地点异常，请填写备注");
                        beizhu.setVisibility(View.VISIBLE);
                        return;
                    }
                    Map<String, String> map = new HashMap<>();
                    map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                    map.put("type", "0");
                    map.put("lng", longtitude);
                    map.put("lat", latitude);
                    map.put("location", location);
                    map.put("signDesc", beizhu.getText().toString().trim());
                    mPresenter.signUpdate(map);
                }
                break;
            case R.id.card2:
                if (SignUtil.isNormalTime(config.getDoneBeginTime(), config.getDoneEndTime(), nowTime.getText().toString().trim()) && SignUtil.isInSignArea(config.getDistance(), config.getLocations(), new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()))) {
                    Map<String, String> map2 = new HashMap<>();
                    map2.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                    map2.put("type", "1");
                    map2.put("lng", longtitude);
                    map2.put("lat", latitude);
                    map2.put("location", location);
                    map2.put("signDesc", beizhu.getText().toString().trim());
                    mPresenter.signUpdate(map2);
                } else {
                    if (beizhu.getText().toString().trim().equals("")) {
                        ToastUtil.displayShortToast("打卡时间或地点异常，请填写备注");
                        beizhu.setVisibility(View.VISIBLE);
                        return;
                    }
                    Map<String, String> map2 = new HashMap<>();
                    map2.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                    map2.put("type", "1");
                    map2.put("lng", longtitude);
                    map2.put("lat", latitude);
                    map2.put("location", location);
                    map2.put("signDesc", beizhu.getText().toString().trim());
                    mPresenter.signUpdate(map2);
                }
                break;
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        location = regeocodeResult.getRegeocodeAddress().getTownship() + regeocodeResult.getRegeocodeAddress().getStreetNumber().getStreet() + regeocodeResult.getRegeocodeAddress().getStreetNumber().getNumber();
//        KLog.i(regeocodeResult.getRegeocodeAddress().getTownship());
//        KLog.i(regeocodeResult.getRegeocodeAddress().getStreetNumber().getStreet());
//        KLog.i(regeocodeResult.getRegeocodeAddress().getStreetNumber().getNumber());
//        KLog.i(regeocodeResult.getRegeocodeAddress().getFormatAddress());
//        KLog.i(regeocodeResult.getRegeocodeAddress().getRoads().get(0).getName());
//        KLog.i(regeocodeResult.getRegeocodeAddress().getDistrict());
//        KLog.i(regeocodeResult.getRegeocodeAddress().getAdCode());
//        KLog.i(regeocodeResult.getRegeocodeAddress().getPois().get(0).getLatLonPoint().getLatitude());
//        KLog.i(regeocodeResult.getRegeocodeAddress().getPois().get(0).getLatLonPoint().getLongitude());
        mLatLonPoint = regeocodeResult.getRegeocodeAddress().getPois().get(0).getLatLonPoint();
        if (config != null && !SignUtil.isInSignArea(config.getDistance(), config.getLocations(), new LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()))) {
            beizhu.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        KLog.i(geocodeResult.getGeocodeAddressList().get(0).getFormatAddress());
    }
}